package com.livvy.exer.test;

import com.livvy.commons.utils.image.AuthCode;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

/**
 * Created with IntelliJ IDEA.
 * User: GuoZheng
 * Date: 13-11-17
 * Time: 下午2:34
 * To change this template use File | Settings | File Templates.
 */
public class ServletImage extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//          PrintWriter out =  response.getWriter();
//          out.println("hello");
//        BufferedImage image = new BufferedImage(60,20,BufferedImage.TYPE_INT_RGB);
//        Graphics g = image.getGraphics();
        Random random = new Random();
//        g.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));
//        g.fillRect(0,0,60,20);
        String str = "QWERTYUIOPASDFGHJKLMNBVCXZ1234567890";
        String number = "";
        for (int i = 0; i < 5;i++) {
            number += str.charAt(random.nextInt(str.length()));
        }
        HttpSession session = request.getSession();
        session.setAttribute("number",number);
        System.out.println(number);
//        g.setColor(new Color(0,0,0));
//        g.drawString(number,10,15);
//        for (int i = 0;i < 5;i++) {
//            g.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));
//            g.drawLine(random.nextInt(60),random.nextInt(20),random.nextInt(60),random.nextInt(20));
//        }
        BufferedImage image = AuthCode.generateAuthCode(number);
        response.setContentType("image/jpeg");
        OutputStream ops = response.getOutputStream();
        javax.imageio.ImageIO.write(image,"jpeg",ops);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
           this.doPost(request,response);
    }
}
